package org.batatasframework.support;

import org.batatasframework.expression.CommandExpression;
import org.batatasframework.expression.CommandExpressionArgument;
import org.batatasframework.properties.PropertiesResource;

import cn.bonoon.kernel.util.StringHelper;

public class PropertyOptionExpression {
	
	public static final String OTPION_COMMENT = " | #";
	
	public static PropertiesResource optionConfig(PropertiesResource pr){
		return pr.setSkipCommentSymbol(OTPION_COMMENT);
	}
	
	public static final String SPLIT_SEPARATOR = "\\s\\|\\s";
	public static final String OPTION_NAME = "options";
	
	
	public static PropertyOptionExpression valueOf(CommandExpression expression){
		return valueOf(expression.getValue(OPTION_NAME));
	}
	
	public static PropertyOptionExpression valueOf(CommandExpressionArgument cvOptions){
		if(cvOptions.disabled()) return null;
		
		PropertyOptionExpression poe = new PropertyOptionExpression();
		String val = cvOptions.getString();
		poe.optionType = cvOptions.getDefaultValue().toEnum(PropertyOptionType.class);
		if(null == poe.optionType) poe.optionType = PropertyOptionType.SINGLE;
		if(val.startsWith(">")){
			int p = val.indexOf(' ');
			poe.offset = StringHelper.toint(val.substring(1, p - 1));
			val = val.substring(p + 1);
		}else{
			poe.offset = poe.optionType.defaultOffset();
		}
		poe.options = val.split(PropertyOptionExpression.SPLIT_SEPARATOR);
		return poe;
	}
	
	private int offset;
	private String[] options;
	private PropertyOptionType optionType;
	
	public int getOffset() {
		return offset;
	}
	
	public String[] getOptions() {
		return options;
	}
	
	public PropertyOptionType getOptionType() {
		return optionType;
	}
}
